package com.hw8.controller;

import com.alibaba.fastjson.JSONObject;
import com.ehw8.base.domain.pojo.Result;
import com.hw8.crond.client.dos.UserInfoDO;
import com.hw8.crond.client.service.UserInfoService;
import com.hw8.mongo.Counters;
import com.hw8.mongoDao.*;
import com.hw8.mongobean.*;
import com.hw8.utils.ErrorEnum;
import com.hw8.utils.ImgUtils;
import com.hw8.utils.MemcacheUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api("朋友圈")
@RestController
@RequestMapping("moments")
@Slf4j
public class QueryController {
    @Resource
    private HttpServletRequest request;
    @Resource
    private MongoTemplate mongoTemplate;
    @Resource
    private FavoriteMongoDao favoriteMongoDao;
    @Resource
    private UserMongoDao userMongoDao;
    @Resource
    private GoodsMongoDao goodsMongoDao;
    @Resource
    private ShareMongoDao shareMongoDao;
    @Resource
    private LastReadMongoDao lastReadMongoDao;
    @Resource
    private SupportMongoDao supportMongoDao;

    @Reference(check = false)
    private UserInfoService userInfoService;


    @ApiOperation("朋友圈未读数")
    @PostMapping("unReadNum")
    public Result unReadNum(){
        Long userId = (Long)request.getAttribute("userId");

        Favorite favorite = new Favorite();
        favorite.setUid(userId);
        favorite = favoriteMongoDao.queryOne(favorite);
        Long lastReadId = 0l;
        if(favorite == null){
            //初始化关注人信息
            List<Long> parentIds = MemcacheUtils.get30TierParentIds(userId);
            favorite = new Favorite();
            favorite.setUid(userId);
            favorite.setFavoriteUids(parentIds);
            favoriteMongoDao.save(favorite);
            //初始化用户头像信息
            UserInfoDO userInfo = userInfoService.getUserInfoByUserId(userId);
            log.info(userInfo.toString());
            User user = new User();
            user.setUid(userId);
            user.setIcon(userInfo.getAvatarUrl());
            user.setNickName(userInfo.getName());
            userMongoDao.save(user);
        }else {
            LastRead lastRead = new LastRead();
            lastRead.setUid(userId);
            lastRead = lastReadMongoDao.queryOne(lastRead);
            if(lastRead != null){
                lastReadId = lastRead.getCid();
            }
        }

        long unReadNum = mongoTemplate.count(new Query(Criteria.where("uid").in(favorite.getFavoriteUids()).and("cid").gt(lastReadId)), Share.class);
        Map map = new HashMap<>(1);
        map.put("unReadNum",unReadNum);
        return Result.success(map);
    }

    @ApiOperation("用户信息初始化")
    @PostMapping("user/init")
    public Result userInit(@RequestBody User user){
        Long userId = (Long)request.getAttribute("userId");
        mongoTemplate.save(user);
        return Result.success("");
    }

    @ApiOperation("朋友圈消息列表")
    @PostMapping("/list")
    public Result list(@RequestBody JSONObject jsonObject){

        Long userId = (Long)request.getAttribute("userId");
        Long lastId = jsonObject.getLong("lastId");
        Integer pageSize = jsonObject.getInteger("pageSize");
        lastId = lastId == null ? 0 : lastId;
        Favorite favorite = new Favorite();
        favorite.setUid(userId);
        favorite = favoriteMongoDao.queryOne(favorite);
        if(favorite == null){
            return Result.fail("没有初始化关注");
        }

        favorite.getFavoriteUids().add(userId);
        List<JSONObject> shareList = getContents(favorite.getFavoriteUids(), pageSize, lastId);

        //更新已读游标
        Counters counters = mongoTemplate.findOne(new Query(Criteria.where("collectionName").is(Share.class.getSimpleName())), Counters.class);
        LastRead srcObj = new LastRead();
        srcObj.setUid(userId);
        //当前最新的Share id
        LastRead targetObj = new LastRead();
        targetObj.setCid(counters == null ? 0 : counters.getNextId() - 1);
        lastReadMongoDao.updateInsert(srcObj,targetObj);

        return Result.success(shareList);
    }

    @ApiOperation("朋友圈消息详情")
    @PostMapping("/content/id")
    public Result getContentById(@RequestBody JSONObject jsonObject){

        Long contentId = jsonObject.getLong("contentId");
        Share share = new Share();
        share.setCid(contentId);
        share = shareMongoDao.queryOne(share);

        JSONObject json = (JSONObject) JSONObject.toJSON(share);
        User user = userMongoDao.queryByUserId(share.getUid());
        if(user != null){
            json.put("icon", ImgUtils.getImgFullUrl(user.getIcon()));
            json.put("nickName",user.getNickName());
        }
        Support support = new Support();
        support.setContentId(share.getCid());
        List<Support> supports = supportMongoDao.getPage(support, 0, 5);
        List<String> suptIcons = supports.stream().map(supt -> {
            User u = userMongoDao.queryByUserId(supt.getUid());
            if (u != null) {
                return ImgUtils.getImgFullUrl(u.getIcon());
            }
            return null;
        }).collect(Collectors.toList());
        json.put("suptIcons",suptIcons);
        Integer goodsId = share.getGoodsId();
        if (goodsId != null) {
            Goods goods = goodsMongoDao.queryByGoodsId(goodsId);
            JSONObject goodsJson = (JSONObject) JSONObject.toJSON(goods);
            json.put("goods", goodsJson);
        }
        return Result.success(json);
    }

    /**
     * 查询朋友圈列表
     * @param userIds 用户id
     * @param pageSize 每页显示数量
     * @return
     */
    private List<JSONObject> getContents(List<Long> userIds,int pageSize,Long lastId){
        Query query = new Query();
        Criteria criteria = Criteria.where("uid").in(userIds);
        if(lastId > 0){
            criteria.and("cid").lt(lastId);
        }
        query.addCriteria(criteria);
        query.with(Sort.by(Sort.Order.desc("_id"))).limit(pageSize);
        List<Share> shares = mongoTemplate.find(query, Share.class);
        List<JSONObject> shareList = shares.stream().map(share -> {
            JSONObject json = (JSONObject) JSONObject.toJSON(share);
            User user = userMongoDao.queryByUserId(share.getUid());
            if(user != null){
                json.put("icon", ImgUtils.getImgFullUrl(user.getIcon()));
                json.put("nickName",user.getNickName());
            }
            Support support = new Support();
            support.setContentId(share.getCid());
            List<Support> supports = supportMongoDao.getPage(support, 0, 5);
            List<String> suptIcons = supports.stream().map(supt -> {
                User u = userMongoDao.queryByUserId(supt.getUid());
                if (u != null) {
                    return ImgUtils.getImgFullUrl(u.getIcon());
                }
                return null;
            }).collect(Collectors.toList());
            json.put("suptIcons",suptIcons);
            Integer goodsId = share.getGoodsId();
            if (goodsId != null) {
                Goods goods = goodsMongoDao.queryByGoodsId(goodsId);
                JSONObject goodsJson = (JSONObject) JSONObject.toJSON(goods);
                json.put("goods", goodsJson);
            }
            return json;
        }).collect(Collectors.toList());
        return shareList;
    }

    @ApiOperation("我的朋友圈消息列表")
    @PostMapping("/mine/list")
    public Result mineList(@RequestBody JSONObject jsonObject){

        Long userId = (Long)request.getAttribute("userId");
        Long lastId = jsonObject.getLong("lastId");
        Integer pageSize = jsonObject.getInteger("pageSize");
        lastId = lastId == null ? 0 : lastId;

        User user = userMongoDao.queryByUserId(userId);
        Query query = new Query();
        Criteria criteria = Criteria.where("uid").is(userId);
        if(lastId > 0){
            criteria.and("cid").lt(lastId);
        }
        query.addCriteria(criteria);
        query.with(Sort.by(Sort.Order.desc("_id"))).limit(pageSize);
        List<Share> shares = mongoTemplate.find(query, Share.class);
        List<JSONObject> goodsList = shares.stream().map(share -> {
            JSONObject json = (JSONObject) JSONObject.toJSON(share);
            if(user != null){
                json.put("icon", ImgUtils.getImgFullUrl(user.getIcon()));
                json.put("nickName",user.getNickName());
            }
            Support support = new Support();
            support.setContentId(share.getCid());
            List<Support> supports = supportMongoDao.getPage(support, 0, 5);
            List<String> suptIcons = supports.stream().map(supt -> {
                User u = userMongoDao.queryByUserId(supt.getUid());
                if (u != null) {
                    return ImgUtils.getImgFullUrl(u.getIcon());
                }
                return null;
            }).collect(Collectors.toList());
            json.put("suptIcons",suptIcons);
            Integer goodsId = share.getGoodsId();
            if (goodsId != null) {
                Goods goods = goodsMongoDao.queryByGoodsId(goodsId);
                JSONObject goodsJson = (JSONObject) JSONObject.toJSON(goods);
                json.put("goods", goodsJson);
            }
            return json;
        }).collect(Collectors.toList());
        return Result.success(goodsList);
    }


    @ApiOperation("评论列表")
    @PostMapping("/content/comment/list")
    public Result<List> commentList(@RequestBody JSONObject jsonObject){
        Long lastId = jsonObject.getLong("lastId");
        Long contentId = jsonObject.getLong("contentId");
        if(contentId == null){
            return ErrorEnum.PARAMETER_ERROR.getResult();
        }
        Integer pageSize = jsonObject.getInteger("pageSize");
        lastId = lastId == null ? 0 : lastId;
        Query query = new Query();
        Criteria criteria = Criteria.where("contentId").is(contentId);
        if(lastId > 0){
            criteria.and("cid").lt(lastId);
        }
        query.addCriteria(criteria);
        query.with(Sort.by(Sort.Order.desc("cid"))).limit(pageSize);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        List<JSONObject> jsonObjects = commentList.stream().map(comment -> {
            JSONObject json = (JSONObject) JSONObject.toJSON(comment);
            User user = userMongoDao.queryByUserId(comment.getUid());
            if (user != null) {
                json.put("icon", ImgUtils.getImgFullUrl(user.getIcon()));
                json.put("nickName", user.getNickName());
            }
            return json;
        }).collect(Collectors.toList());
        return Result.success(jsonObjects);
    }


    @ApiOperation("点赞列表")
    @PostMapping("/content/like/list")
    public Result commentLikeList(@RequestBody JSONObject jsonObject){
        Long lastId = jsonObject.getLong("lastId");
        Long contentId = jsonObject.getLong("contentId");
        if(contentId == null){
            return ErrorEnum.PARAMETER_ERROR.getResult();
        }
        Integer pageSize = jsonObject.getInteger("pageSize");
        lastId = lastId == null ? 0 : lastId;
        Query query = new Query();
        Criteria criteria = Criteria.where("contentId").is(contentId);
        if(lastId > 0){
            criteria.and("sid").lt(lastId);
        }
        query.addCriteria(criteria);
        query.with(Sort.by(Sort.Order.desc("id"))).limit(pageSize);
        List<Support> supportList = mongoTemplate.find(query, Support.class);
        List<JSONObject> jsonObjects = supportList.stream().map(comment -> {
            JSONObject json = (JSONObject) JSONObject.toJSON(comment);
            User user = userMongoDao.queryByUserId(comment.getUid());
            if (user != null) {
                json.put("icon", ImgUtils.getImgFullUrl(user.getIcon()));
                json.put("nickName", user.getNickName());
            }
            return json;
        }).collect(Collectors.toList());
        return Result.success(jsonObjects);
    }


    @ApiOperation("个人背景图片")
    @PostMapping("/mine/bgPic/get")
    public Result getBgPic(){
        Long userId = (Long)request.getAttribute("userId");
        User user = userMongoDao.queryByUserId(userId);
        Map map = new HashMap(1);
        if (user != null) {
            map.put("bgPic", ImgUtils.getImgFullUrl(user.getBgPic()));
        }
        return Result.success(map);
    }

}
